export const baseURL = 'http://localhost:5430'; // 基础 URL

// 封装请求方法
const request = async (url, method, data) => {
  console.log(`API请求: ${method} ${url}`, data ? data : '');
  
  const options = {
    method,
    headers: {
      'Content-Type': 'application/json'
    }
  };

  if (data) {
    options.body = JSON.stringify(data);
  }

  try {
    const fullUrl = `${baseURL}${url}`;
    console.log('完整请求URL:', fullUrl);
    
    const response = await fetch(fullUrl, options);
    const responseData = await response.json();
    
    console.log(`API响应: ${method} ${url}`, responseData);
    return responseData;
  } catch (error) {
    console.error('API请求错误:', error, `${method} ${url}`);
    return { result: 'fail', message: '网络请求失败' };
  }
};

// 小组管理API
export const groupApi = {
  // 创建小组
  createGroup: (data) => request('/CodeQuestion-service/groups/create', 'POST', data),
  
  // 更新小组信息
  updateGroup: (data) => request('/CodeQuestion-service/groups/update', 'PUT', data),
  
  // 获取小组详情
  getGroupDetail: (id) => request(`/CodeQuestion-service/groups/${id}`, 'GET'),
  
  // 获取所有小组列表
  getGroupList: (pageNum = 1, pageSize = 10) => 
    request(`/CodeQuestion-service/groups/list?pageNum=${pageNum}&pageSize=${pageSize}`, 'GET'),
  
  // 获取我创建的小组
  getMyCreatedGroups: (userId) => request(`/CodeQuestion-service/groups/my-created/${userId}`, 'GET'),
  
  // 获取我加入的小组
  getMyJoinedGroups: (userId) => request(`/CodeQuestion-service/groups/my-joined/${userId}`, 'GET'),
  
  // 申请加入小组
  joinGroup: (groupId, userId) => request('/CodeQuestion-service/groups/join', 'POST', { groupId, userId }),
  
  // 获取小组成员列表
  getGroupMembers: (groupId) => request(`/CodeQuestion-service/groups/${groupId}/members`, 'GET'),
  
  // 获取用户在小组中的角色
  getUserRole: (groupId, userId) => request(`/CodeQuestion-service/groups/${groupId}/user-role/${userId}`, 'GET'),
  
  // 获取待审核成员列表
  getPendingMembers: (groupId) => request(`/CodeQuestion-service/groups/${groupId}/pending-members`, 'GET'),
  
  // 批准加入申请
  approveJoin: (groupId, userId, operatorId) => 
    request('/CodeQuestion-service/groups/approve-join', 'POST', { groupId, userId, operatorId }),
  
  // 拒绝加入申请
  rejectJoin: (groupId, userId, operatorId) => 
    request('/CodeQuestion-service/groups/reject-join', 'POST', { groupId, userId, operatorId }),
  
  // 移除小组成员
  removeMember: (groupId, userId, operatorId) => 
    request('/CodeQuestion-service/groups/remove-member', 'POST', { groupId, userId, operatorId }),
    
  // 获取小组题库列表
  getGroupProblems: (groupId) => request(`/CodeQuestion-service/problems/group/${groupId}`, 'GET'),
  
  // 获取小组题库列表（新的正确路径）
  getGroupProblemList: (userId, groupId) => request(`/CodeQuestion-service/problems/getGroupProblems?user_id=${userId}&group_id=${groupId}`, 'GET'),
  
  // 获取小组题库列表（最新版本，无需user_id）
  getGroupProblemList2: (groupId) => request(`/CodeQuestion-service/problems/getGroupProblems?group_id=${groupId}`, 'GET')
};

// 小组任务API
export const taskApi = {
  // 创建任务
  createTask: (data) => {
    console.log('创建任务请求数据:', data);
    return request('/CodeQuestion-service/group-tasks/create', 'POST', data);
  },
  
  // 更新任务
  updateTask: (data) => request('/CodeQuestion-service/group-tasks/update', 'PUT', data),
  
  // 获取任务详情
  getTaskDetail: (id) => {
    console.log('获取任务详情, ID:', id);
    return request(`/CodeQuestion-service/group-tasks/${id}`, 'GET');
  },
  
  // 获取小组任务列表
  getGroupTasks: (groupId) => {
    console.log('获取小组任务列表, 小组ID:', groupId);
    return request(`/CodeQuestion-service/group-tasks/group/${groupId}`, 'GET');
  },
  
  // 分配任务
  assignTask: (taskId, userId) => {
    console.log('分配任务, 任务ID:', taskId, '用户ID:', userId);
    return request('/CodeQuestion-service/group-tasks/assign', 'POST', { task_id: taskId, user_id: userId, completed: false });
  },
  
  // 完成任务
  completeTask: (taskId, userId) => {
    console.log('完成任务, 任务ID:', taskId, '用户ID:', userId);
    return request(`/CodeQuestion-service/group-tasks/complete?taskId=${taskId}&userId=${userId}`, 'POST');
  },
  
  // 获取我的任务
  getMyTasks: (userId) => request(`/CodeQuestion-service/group-tasks/my-tasks/${userId}`, 'GET'),
  
  // 提交任务（使用FormData，不能用JSON）
  submitTask: async (formData) => {
    console.log('提交任务:', formData);
    try {
      const response = await fetch(`${baseURL}/CodeQuestion-service/task-submissions/submit`, {
        method: 'POST',
        body: formData
      });
      const data = await response.json();
      console.log('提交任务响应:', data);
      return data;
    } catch (error) {
      console.error('提交任务错误:', error);
      return { result: 'fail', message: '网络请求失败' };
    }
  },
  
  // 获取任务的所有提交
  getTaskSubmissions: (taskId) => request(`/CodeQuestion-service/task-submissions/task/${taskId}`, 'GET'),
  
  // 获取用户对某任务的提交
  getAssignmentSubmission: (assignmentId) => request(`/CodeQuestion-service/task-submissions/assignment/${assignmentId}`, 'GET'),
  
  // 审核任务提交
  reviewSubmission: (id, status, comment) => 
    request(`/CodeQuestion-service/task-submissions/review/${id}?status=${status}&comment=${comment}`, 'POST'),
  
  // 上传任务图片
  uploadTaskImage: async (file) => {
    const formData = new FormData();
    formData.append('image', file);
    
    try {
      const response = await fetch(`${baseURL}/CodeQuestion-service/task-submissions/upload-image`, {
        method: 'POST',
        body: formData
      });
      const data = await response.json();
      console.log('上传任务图片响应:', data);
      return data;
    } catch (error) {
      console.error('上传任务图片错误:', error);
      return { result: 'fail', message: '网络请求失败' };
    }
  }
};

// 公告相关API
export const announcementApi = {
  // 获取最近公告
  getRecentAnnouncements: (limit = 5) => 
    request(`/CodeQuestion-service/announcements/recent?limit=${limit}`, 'GET'),
    
  // 获取公告列表
  getAnnouncements: (page = 1, size = 10) => 
    request(`/CodeQuestion-service/announcements?page=${page}&size=${size}`, 'GET')
};

// 活动相关API
export const activityApi = {
  // 获取用户的最近活动
  getUserActivities: (userId, limit = 5) => 
    request(`/CodeQuestion-service/activities/user/${userId}?limit=${limit}`, 'GET'),
    
  // 获取最近的全局活动
  getRecentActivities: (limit = 5) => 
    request(`/CodeQuestion-service/activities/recent?limit=${limit}`, 'GET')
};